<?php
class ModelShippingSpeedy extends Model {
	function getQuote($address) {
		$this->language->load('shipping/speedy');

		if (isset($address['validate'])) {
			$status = true;
		} else {
			$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('speedy_geo_zone_id') . "' AND country_id = '" . (int)$address['country_id'] . "' AND (zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')");

			if (!$this->config->get('speedy_geo_zone_id')) {
				$status = true;
			} elseif ($query->num_rows) {
				$status = true;
			} else {
				$status = false;
			}
		}

		$method_data = array();

		if ($status) {
			$quote_data = array();

			$quote_data['speedy'] = array(
				'code'         => 'speedy.speedy',
				'title'        => $this->language->get('text_description'),
				'cost'         => 0.00,
				'tax_class_id' => 0,
				'text'         => $this->currency->format(0.00)
			);

			$method_data = array(
				'code'       => 'speedy',
				'title'      => $this->language->get('text_title'),
				'quote'      => $quote_data,
				'sort_order' => $this->config->get('speedy_sort_order'),
				'error'      => false
			);

			if (isset($this->session->data['speedy']) &&
				($this->customer->isLogged() && isset($this->session->data['shipping_address_id'])
				&& isset($this->session->data['speedy_customer']) &&
				$this->session->data['speedy_customer']['shipping_address_id'] == $this->session->data['shipping_address_id'] ||
				isset($this->session->data['guest']) && isset($this->session->data['speedy_guest']) &&
				$this->session->data['speedy_guest']['city'] == $this->session->data['guest']['shipping']['city'] &&
				$this->session->data['speedy_guest']['postcode'] == $this->session->data['guest']['shipping']['postcode'])) {
				require_once(DIR_SYSTEM . 'library/speedy.php');
				$speedy = new Speedy($this->registry);

				$total = $this->cart->getTotal();
				$totalNoShipping = $total;
				$total = $this->currency->format($total, $this->config->get('speedy_currency'), '', false);
				$weight = 0;

				foreach ($this->cart->getProducts() as $product) {
					if ($product['shipping']) {
						//if (!$this->config->get('speedy_documents')) {
							$product_weight = (float)$product['weight'];
							if (!empty($product_weight)) {
								$weight += $this->weight->convert($product['weight'], $product['weight_class_id'], 1);
							} else {
								$weight += ($this->config->get('speedy_default_weight') * $product['quantity']);
							}
						//}
					} else {
						$totalNoShipping -= $this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity'];
					}
				}

				if ($this->config->get('speedy_documents') && (float)$weight > 0.25) {
					$weight = 0.25;
				}

				$this->session->data['speedy']['total'] = $total;
				$this->session->data['speedy']['totalNoShipping'] = $this->currency->format($totalNoShipping, $this->config->get('speedy_currency'), '', false);
				$this->session->data['speedy']['weight'] = $weight;
				$this->session->data['speedy']['count'] = 1; //$this->cart->countProducts();
				$this->session->data['speedy']['taking_date'] = ($this->config->get('speedy_taking_date') ? strtotime('+' . (int)$this->config->get('speedy_taking_date') . ' day', mktime(9, 0, 0)) : time());

				if ($this->config->get('speedy_pricing') == 'fixed' || $this->config->get('speedy_pricing') == 'calculator_fixed') {
					$this->session->data['speedy']['total'] += $this->config->get('speedy_fixed_price');
				}

				$this->session->data['speedy']['fixed_time'] = null;

				if (!$this->config->get('speedy_cod_status')) {
					$this->session->data['speedy']['cod'] = false;
				}

				$methods = $speedy->calculate($this->session->data['speedy']);

				$this->session->data['speedy']['methods_fixed_time'] = array();

				if (isset($this->session->data['speedy']['fixed_time_cb'])) {
					$methods_fixed_time = $speedy->calculate(array_merge($this->session->data['speedy'], array('fixed_time' => $this->session->data['speedy']['fixed_time_hour'] . $this->session->data['speedy']['fixed_time_min'])));
				} else {
					$methods_fixed_time = $speedy->calculate(array_merge($this->session->data['speedy'], array('fixed_time' => '1030')));
				}

				$services = $speedy->getServices();
				$methods_count = 0;

				foreach ($methods_fixed_time as $method) {
					if (!$method->getErrorDescription()) {
						$this->session->data['speedy']['methods_fixed_time'][$method->getServiceTypeId()] = $method->getResultInfo()->getAmounts()->getTotal();
					}
				}
                                
				if (!$speedy->getError()) {
					foreach ($methods as $method) {
						if (!$method->getErrorDescription()) {
							if (($this->config->get('speedy_pricing') == 'free') && ($total >= (float)$this->config->get('speedy_free_shipping_total')) &&
								($method->getServiceTypeId() == $this->config->get('speedy_free_method_city') || $method->getServiceTypeId() == $this->config->get('speedy_free_method_intercity'))) {
								$method_total = 0;
							} elseif ($this->config->get('speedy_pricing') == 'fixed') {
								$method_total = $this->config->get('speedy_fixed_price');
							} else {
								if (isset($this->session->data['speedy']['fixed_time_cb']) && isset($this->session->data['speedy']['methods_fixed_time'][$method->getServiceTypeId()])) {
									$method_total = $this->session->data['speedy']['methods_fixed_time'][$method->getServiceTypeId()];
                                                                } else {
									$method_total = $method->getResultInfo()->getAmounts()->getTotal();
								}

								if ($this->config->get('speedy_pricing') == 'calculator_fixed') {
									$method_total += $this->config->get('speedy_fixed_price');
								}
							}
							$method_total = $this->currency->convert((float)$method_total, $this->config->get('speedy_currency'), $this->config->get('config_currency'));

							$quote_data[$method->getServiceTypeId()] = array(
								'code'         => 'speedy.' . $method->getServiceTypeId(),
								'title'        => $this->language->get('text_description') . ' - ' . $services[$method->getServiceTypeId()],
								'cost'         => $method_total,
								'tax_class_id' => 0,
								'text'         => $this->currency->format($method_total)
							);

							$methods_count++;
						}
					}

					if ($methods_count) {
						unset($quote_data['speedy']);
						$method_data['quote'] = $quote_data;
                                        }					
				} else {
					$method_data['speedy_error'] = $speedy->getError();
				}
			} else {
				$method_data['speedy_error'] = $this->language->get('error_calculate');
				unset($this->session->data['speedy']);
			}
		}

		if (isset($method_data['speedy_error'])) {
			$method_data['quote']['speedy']['text'] = '';
		}

		return $method_data;
	}

	public function addAddress($address_id, $data) {
		$this->db->query("DELETE FROM " . DB_PREFIX . "speedy_address WHERE address_id = '" . (int)$address_id . "' AND customer_id = '" . (int)$this->customer->getId() . "'");

		$this->db->query("INSERT INTO " . DB_PREFIX . "speedy_address SET address_id = '" . (int)$address_id . "', customer_id = '" . (int)$this->customer->getId() . "', postcode = '" . $this->db->escape($data['postcode']) . "', city = '" . $this->db->escape($data['city']) . "', city_id = '" . (int)$data['city_id'] . "', city_nomenclature = '" . $this->db->escape($data['city_nomenclature']) . "', to_office = '" . (int)$data['to_office'] . "', office_id = '" . (int)$data['office_id'] . "', quarter = '" . $this->db->escape($data['quarter']) . "', quarter_id = '" . (int)$data['quarter_id'] . "', street = '" . $this->db->escape($data['street']) . "', street_id = '" . (int)$data['street_id'] . "', street_no = '" . $this->db->escape($data['street_no']) . "', block_no = '" . $this->db->escape($data['block_no']) . "', entrance_no = '" . $this->db->escape($data['entrance_no']) . "', floor_no = '" . $this->db->escape($data['floor_no']) . "', apartment_no = '" . $this->db->escape($data['apartment_no']) . "', note = '" . $this->db->escape($data['note']) . "'");
	}

	public function getAddress($address_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "speedy_address WHERE address_id = '" . (int)$address_id . "' AND customer_id = '" . (int)$this->customer->getId() . "'");

		return $query->row;
	}

	public function addOrder($order_id, $data) {
                $data['price_gen_method'] = $this->config->get('speedy_pricing');
		$this->db->query("INSERT INTO " . DB_PREFIX . "speedy_order SET order_id = '" . (int)$order_id . "', data = '" . $this->db->escape(serialize($data)) . "'");
	}
}
?>
